<template>
	<BasicModal @register="registerModalInner" :title="getTitle" @ok="handleSubmit">
		<BasicForm @register="registerForm"></BasicForm>
	</BasicModal>
</template>
<script lang="ts">
import { BasicModal, BasicForm } from '#/components';
import { useForm } from '#/hooks';
import { useModalInner } from '#/Modal';
import type { FormSchema } from '#/types';
import { addOrEditUser, getAllRoles, getPrincipaltree } from '@/api/demo';
import { useMessage } from '@/hooks/web/useMessage';
import { computed, defineComponent, ref, unref } from 'vue';

const formSchema: FormSchema[] = [
	{
		field: 'username',
		label: '用户名',
		component: 'Input',
		required: true,
	},
	{
		field: 'name',
		label: '姓名',
		component: 'Input',
		required: true,
	},
	{
		field: 'roleIdList',
		label: '角色',
		component: 'ApiSelect',
		required: true,
		componentProps: {
			api: getAllRoles,
			labelField: 'roleName',
			valueField: 'roleId',
			mode: 'multiple',
		},
	},
	{
		field: 'posts',
		label: '职位',
		component: 'Input',
		required: true,
	},
	{
		field: 'deptId',
		label: '部门',
		component: 'ApiTreeSelect',
		required: true,
		componentProps: {
			api: getPrincipaltree,
			fieldNames: { key: 'id', value: 'deptId', label: 'name' },
		},
	},
	{
		field: 'mobile',
		label: '电话',
		component: 'Input',
		rules: [{ len: 11, pattern: /^1[3456789]\d{9}$/, message: '请输入正确的电话号码' }],
		componentProps: {
			maxLength: 11,
		},
	},
];

export default defineComponent({
	name: 'TreeAndTableModal',
	components: { BasicModal, BasicForm },
	emits: ['success', 'register'],
	setup(_, { emit }) {
		const isUpdate = ref(true);
		const userId = ref();

		const { createMessage } = useMessage();

		const [registerModalInner, { closeModal }] = useModalInner(data => {
			resetFields();
			isUpdate.value = !!data?.isUpdate;

			if (unref(isUpdate)) {
				userId.value = data.record.userId;
				setFieldsValue({ ...data.record });
			}
		});

		const [registerForm, { setFieldsValue, validate, resetFields }] = useForm({
			schemas: formSchema,
			showActionButtonGroup: false,
			baseRowStyle: {
				'justify-content': 'space-around',
			},
			baseColProps: {
				span: 20,
			},
		});

		const getTitle = computed(() => (unref(isUpdate) ? '编辑人员' : '新增人员'));

		async function handleSubmit() {
			try {
				const values = await validate();
				unref(isUpdate) && (values.userId = userId.value);
				await addOrEditUser(isUpdate.value, values);
				closeModal();
				emit('success');
			} catch (_err) {
				createMessage.error('操作失败');
			}
		}

		return {
			registerModalInner,
			registerForm,
			getTitle,
			handleSubmit,
		};
	},
});
</script>
<style lang="less" scoped></style>
